package com.cellulam.framework.core.utils;

import com.cellulam.framework.core.exceptions.SysException;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.net.URL;

public class FileUtils {
    public static String getExtension(String fileName) {
        if (StringUtils.isEmpty(fileName)) {
            return null;
        }
        return StringUtils.substringAfterLast(fileName, ".");
    }

    /**
     * 下载文件，如果遇到同名文件则覆盖
     *
     * @param url
     * @param dir
     * @param fileName
     * @return
     */
    public static File downloadFile(String url, String dir, String fileName) {
        return downloadFile(url, dir, fileName, true);
    }

    /**
     * 下载文件
     *
     * @param url
     * @param dir
     * @param fileName
     * @param override 是否覆盖文件，为false时，直接取原文件，不再重新从URL下载
     * @return
     */
    public static File downloadFile(String url, String dir, String fileName, boolean override) {
        try {
            File file = new File(dir + fileName);

            if (override) {
                file.deleteOnExit();
            } else if (file.exists()) {
                return file;
            }

            URL httpUrl = new URL(url);
            File dirFile = new File(dir);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
            org.apache.commons.io.FileUtils.copyURLToFile(httpUrl, file);
            return file;
        } catch (Exception e) {
            throw new SysException("下载文件失败", e);
        }
    }

}
